import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Home from '@/views/home.vue'
import ErrorPage from '@/components/404.vue'
import { getLocal } from '@/utils/local'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    children: [
      {
        path: '/welcome',
        name: 'Welcome',
        component: () => import('@/views/welcome.vue')
      },
      {
        path: '/users',
        name: 'Users',
        component: () => import('@/views/users/Users.vue')
      },
      {
        path: '/goods',
        name: 'Goods',
        component: () => import('@/views/goods/Goods.vue')
      },
      {
        path: '/lang',
        name: 'Lang',
        component: () => import('@/views/lang/Lang.vue')
      },
      {
        path: '/permits',
        name: 'Permits',
        component: () => import('@/views/permits/Permits.vue')
      },
      {
        path: '/roles',
        name: 'Roles',
        component: () => import('@/views/permits/Roles.vue')
      },
      {
        path: '/other',
        name: 'Other',
        component: () => import('@/views/other/Other.vue')
      }
    ]
  },
  {
    path: "/:pathMatch(.*)*",
    name: '404',
    component: ErrorPage
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

const LOGIN_PAGE_NAME = 'login'

router.beforeEach((to, from, next) => {
  const token = getLocal('token')
  if (!token && to.name != LOGIN_PAGE_NAME) {
    next({ name: LOGIN_PAGE_NAME })
  } else {
    next()
  }
})

export default router
